#唐门优测
#道长最帅666
from common.read_yaml import get_yaml_filepath
from common.readCofig import Envison
import requests
import json
from common.readCofig import env
import time
from urllib.parse import urlencode

data = get_yaml_filepath(Envison=Envison)

class HttpClient:
    def __init__(self):
        self.host = data['admin_host']

    default_header = {
        "Content-Type":"application/json"
    }

    def send(self,url,body = {},method = {},headers = {},session = '',x_token = ''):

        headers.update(self.default_header)
        if x_token:
            headers['Authorization'] = 'Bearer ' + x_token.strip('"')#strip() 方法用于移除字符串头尾指点的字符（默认空格或换行符）或字符序列
        if session:
            headers['Session'] = "Bearer " + session

        if method == 'get':
            result = requests.get(url,params= body,headers = headers)
        elif method == 'post':
            result = requests.post(url,json=body,headers = headers)
        elif method == 'patch':
            result = requests.patch(url,data = json.dumps(body),headers = headers)

        return result.json()

    def get_full_url(self,url,etc = {}, replace = {},h = ''):
        if h:
            host = h.rstrip('/') #rstrip() 删除string 字符串末尾的指定字符（默认为空格）
        else:
            host = self.host.rstrip('/')
        url = url.lstrip('/') #lstrip() 方法用于截掉字符串左边的空格或指定字符
        full_url = host + '/' + url
        full_url += "?platform={}&time=".format(env) + str(int(round(time.time() * 1000)))
        print(full_url)

        if etc:
            s = urlencode(etc) #urlencode urllib库里面有个urlencode函数，可以把key-vaule这样的键值对转换成我们想要的一个格式，返回的是a=1&b=2这样的字符串
            full_url += '&' + s

        if replace:
            full_url = str.format(full_url,replace)#str.format()方法通过字符串中的花括号{}来识别替换字段 从而完成字符串的格式化。

        return full_url

if __name__ == '__main__':
    client = HttpClient()
    re = client.send(url='http://121.37.169.128:8201/mall-member/sso/login?password=123456&username=admin',
                     body={},method='post',headers={"Content-Type":"application/json"})
    print(re)
    print(str(int(round(time.time() * 1000))))
    print(str(int(round(time.time()))))


